/**
 * Eclipse Outliner
 * Copyright (C) 2006 Jeff Mesnil
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
package net.jmesnil.outliner.ui.actions;

import net.jmesnil.opml.core.IOPML;
import net.jmesnil.opml.core.OPMLPlugin;
import net.jmesnil.outliner.ui.editors.OutlinerEditor;
import net.jmesnil.outliner.ui.internal.OutlinerEditorInput;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;

public class OPMLCreateNewAction extends Action implements IWorkbenchAction {

    public static final String ID = "net.jmesnil.opml.ui.actions.OPMLCreateNewAction";

    private IWorkbenchWindow window;

    public OPMLCreateNewAction(IWorkbenchWindow window) {
        this.window = window;
        setId(ID);
        setActionDefinitionId(ID);

        setDescription("&Create New OPML");
        setText("New");
    }

    public void dispose() {
        window = null;
    }

    public void selectionChanged(IAction action, ISelection selection) {
    }

    public void run(IAction action) {
        run();
    }

    public void run() {
        IOPML opml = OPMLPlugin.getDefault().createOPML();
        opml.getBody().appendNewOutline("");
        IEditorInput input = new OutlinerEditorInput(opml);
        IWorkbenchPage page = window.getActivePage();
        try {
            page.openEditor(input, OutlinerEditor.ID);
        } catch (PartInitException e) {
            MessageDialog.openError(window.getShell(), "New OPML Error", e
                    .getMessage());
        }
    }
}
